<template>
    <div>
        <!-- destroyOnClose 设为true关闭时销毁元素 -->
        <a-modal style="top: 5vh" width="35vw" ok-text="提交" cancel-text="取消" ref="modalRef" :visible="isShow"
            :destroyOnClose="true" :wrap-style="{ overflow: 'hidden' }" @ok="handleOk" @cancel="cancelAdd">

            <div class="container-AddCondition">
                <a-form class="form" :model="formState" :rules="rules" ref="formRef">
                    <div class="form-main" @finish="onFinish" @finishFailed="onFinishFailed">
                        <!-- 选择事件级别 -->
                        <a-form-item name="eventLevel" label="事件等级" has-feedback
                            :rules="[{ required: true, message: '请选择事件等级' }]">
                            <a-select placeholder="请选择事件等级" v-model:value="formState.eventLevel">
                                <a-select-option v-for="(item, index) in eventLevel" :key="index" :label="item"
                                    :value="item">{{
                                            item
                                    }}</a-select-option>
                            </a-select>
                        </a-form-item>
                        <!-- 选择事件类型 -->
                        <a-form-item name="eventTypes" label="事件类型" has-feedback
                            :rules="[{ required: true, message: '请选择事件类型' }]">
                            <a-select placeholder="请选择事件类型" v-model:value="formState.eventTypes">
                                <a-select-option v-for="(item, index) in eventTypes" :key="index" :label="item"
                                    :value="item">{{
                                            item
                                    }}</a-select-option>
                            </a-select>
                        </a-form-item>
                        <!-- 添加事件编号 -->
                        <a-form-item label="事件编号" name="eventNum">
                            <a-input placeholder="请输入事件编号" v-model:value="formState.eventNum" />
                        </a-form-item>
                        <!-- 添加事件地址 -->
                        <a-form-item label="发生地点" name="address">
                            <a-input placeholder="请输入事件发生的地点(包含事故路段)" v-model:value="formState.address" />
                        </a-form-item>
                        <!-- 填写建筑标识 -->
                        <!-- <a-form-item label="&nbsp&nbsp&nbsp建筑标识" name="tag">
                                            <a-input placeholder="请输入事故最近的建筑标识" v-model:value="formState.tag" />
                                        </a-form-item> -->
                        <!-- 选择发生时间 -->
                        <a-form-item name="date" label="发生时间" v-bind="config">
                            <a-date-picker class="time-item" show-time format="YYYY-MM-DD HH:mm:ss"
                                value-format="YYYY-MM-DD HH:mm:ss" v-model:value="formState['date']" />
                        </a-form-item>
                        <!-- 处理状态 -->
                        <a-form-item name="eventState" label="事件状态" has-feedback
                            :rules="[{ required: true, message: '请选择事件状态' }]">
                            <a-select placeholder="请选择事件状态" v-model:value="formState.eventState">
                                <a-select-option v-for="(item, index) in eventState" :key="index" :label="item"
                                    :value="item">{{
                                            item
                                    }}</a-select-option>
                            </a-select>
                        </a-form-item>
                        <!-- 填写事件描述 -->
                        <!-- <a-form-item label="&nbsp&nbsp&nbsp事件描述" name="description">
                                            <a-input placeholder="请输入事故的具体信息" v-model:value="formState.description" />
                                        </a-form-item>
                                         -->
                        <!-- 车牌号 -->
                        <a-form-item label="&nbsp&nbsp&nbsp&nbsp车牌号" name="carNum">
                            <a-input placeholder="请输入车牌号" v-model:value="formState.carNum" />
                        </a-form-item>
                        <!-- 驾驶员 -->
                        <a-form-item label="&nbsp&nbsp&nbsp&nbsp驾驶员" name="carDrive">
                            <a-input placeholder="请输入驾驶员名称" v-model:value="formState.carDrive" />
                        </a-form-item>
                        <!-- <a-form-item :wrapper-col="{ offset: 8, span: 16 }">
                            <a-button type="primary" html-type="submit">Submit</a-button>
                        </a-form-item> -->
                    </div>

                </a-form>
            </div>


            <!-- 标题 -->
            <template #title>
                <div v-if="addUpdate" ref="modalTitleRef" style="width: 100%; cursor: move">事件添加
                </div>
                <div v-else ref="modalTitleRef" style="width: 100%; cursor: move">事件更新
                </div>
            </template>
            <!-- 拖拽相关 -->
            <template #modalRender="{ originVNode }">
                <div :style="transformStyle">
                    <component :is="originVNode" />
                </div>
            </template>
        </a-modal>
    </div>
</template>
<script setup>
/* message弹窗 */
import { message } from 'ant-design-vue';
import 'ant-design-vue/es/message/style/css';
import { ref, computed, reactive, watch, watchEffect, toRefs, onMounted } from 'vue';
import { Point } from 'assets/libs/utils/ES6PointAdd_Query.js'
import { Update } from 'assets/libs/utils/ES6Update.js'
/* 按需加载的vue组件库 */
import { useDraggable } from '@vueuse/core';
import { Form } from 'ant-design-vue';
/* 导入封装的事件axios请求 */
import { getEventAudit } from 'request/event'
import { useNow, useDateFormat } from '@vueuse/core'
const useForm = Form.useForm;
let Fid
/* 接收父组件的数据 */
const props = defineProps({
    isShow: {
        type: Boolean,
        default: false
    },
    position: {
        type: Array,
        default: []
    },
    addUpdate: {
        type: Boolean,
        default: true
    },
    updateData: {
        type: Array,
        default: []
    },
})
/* 拿到父组件的数据 */
let { isShow, addUpdate, updateData } = toRefs(props);
/* 取消添加 */
const emit = defineEmits(['changeIsShow'])
const cancelAdd = () => {
    emit('changeIsShow', false)
    if (addUpdate.value) {
        message.info("取消添加事件")
    } else {
        message.info("取消更新事件")
    }
    /* 重置表单 */
    formRef.value.resetFields();
}
/* 点击验证信息是否完成 */
/* 提交请求到中地数据库添加点要素 */
const handleOk = e => {
    formRef.value.validateFields().then((suc) => {
        console.log("这是什么");
    }, (info) => {
        console.log(info);
        const { errorFields, values } = info
        if (errorFields.length == 0) {
            /* 表单信息 */
            console.log(values);
            switch (values.eventState) {
                case "待处理":
                    values.eventState = 0
                    break
                case "处理中":
                    values.eventState = 1
                    break
                case "已归档":
                    values.eventState = 2
                    break
            }
            switch (values.eventLevel) {
                case "轻微事故":
                    values.eventLevel = 1
                    console.log(values.eventLevel);
                    break
                case "一般事故":
                    values.eventLevel = 2
                    console.log(values.eventLevel);
                    break
                case "重大事故":
                    values.eventLevel = 3
                    console.log(values.eventLevel);
                    break
                case "特大事故":
                    values.eventLevel = 4
                    console.log(values.eventLevel);
                    break
            }
            // console.log(values.eventLevel);
            /* 位置信息 */
            console.log(props.position);
            /* 把事件信息加入数组 */
            const attr = [
                values.eventNum,
                values.eventTypes,
                values.eventLevel,
                values.date,
                values.address,
                values.carNum,
                values.carDrive,
                values.eventState,
                0
            ]
            console.log(attr);
            /* 根据信息调用中地接口添加事件点要素 */
            if (addUpdate.value) {
                console.log('事件添加发送');
                Point.add({
                    position: props.position,
                    attr: attr,
                    service: {
                        name: 'guanggu',
                        layerId: 2
                    },
                })
            } else {
                console.log('事件更新发送');
                Update.ByFid({
                    Fid,
                    attr: [values.eventState],
                    service: {
                        name: 'guanggu',
                        layerId: 2
                    },
                    docName: docLayer
                })
                message.success('事件更新成功')
            }
            /* 添加成功关闭对话框 */
            emit('changeIsShow', false)
            /* 重置表单 */
            formRef.value.resetFields();
        } else {
            message.warning("请填写完整信息")
        }
    })

};

const onFinish = values => {
    console.log('Success:', values);
};
const onFinishFailed = errorInfo => {
    console.log('Failed:', errorInfo);
};

/* -------------------表单---------------------- */
const formRef = ref();
/* 定义表单元素 */
/* 生成事件编号 */
const formatted = useDateFormat(useNow(), 'YYYYMMDDHHmmss')
console.log(formatted.value);
const eventNum = "SJ" + formatted.value
const formState = reactive({
    address: "",
    date: "",
    eventTypes: "",
    dialogVisible: false,
    eventLevel: "",
    eventNum: eventNum,
    eventState: "待处理",
    carNum: "",
    carDrive: "",
});
/* 获取最新的一条已审核的数据填写到表单 */
watch(isShow, async () => {
    /* 判断是更新还是添加状态 */
    /* 添加状态 */
    if (addUpdate.value) {
        console.log("添加");
        const { data } = await getEventAudit()
        if (data.result.length != 0) {
            console.log(data.result);
            formState.address = data.result[0].event_addr
            formState.date = data.result[0].event_time
            formState.eventTypes = data.result[0].event_type
            formState.address = data.result[0].event_addr
            console.log(formState);
        }
    } else {
        console.log('更新');
        console.log(updateData.value[0].AttValue)
        console.log(updateData.value[0].FID)
        const data = updateData.value[0].AttValue
        Fid = updateData.value[0].FID
        switch (data[7]) {
            case '0':
                data[7] = "待处理"
                break
            case '1':
                data[7] = "处理中"
                break
            case '2':
                data[7] = "已归档"
                break
        }
        switch (data[2]) {
            case '1':
                data[2] = "已归档"
                console.log(data[2]);
                break
            case '2':
                data[2] = "一般事故"
                console.log(data[2]);
                break
            case '3':
                data[2] = "重大事故"
                console.log(data[2]);
                break
            case '4':
                data[2] = "特大事故"
                console.log(data[2]);
                break
        }
        /* 更新表单数据 */
        formState.eventNum = data[0]
        formState.eventTypes = data[1]
        formState.eventLevel = data[2]
        formState.date = data[3]
        formState.address = data[4]
        formState.carNum = data[5]
        formState.carDrive = data[6]
        formState.eventState = data[7]
    }

})

/* 事件类型选择 */
const eventTypes = reactive([
    "碰撞",
    "刮擦",
    "追尾",
    "碾压",
    "翻车",
    "失火",
    "其他",
]);
const eventLevel = reactive([
    "轻微事故",
    "一般事故",
    "重大事故",
    "特大事故",
]);
const eventState = reactive([
    "待处理",
    "处理中",
    "已归档",
]);
/* 规则校验 */
const rules = ref({
    address: [
        {
            required: true,
            message: "请输入事件地址",
            trigger: "blur",
        },
    ],
    eventNum: [
        {
            required: true,
            message: "请输入事件编号",
            trigger: "blur",
        },
    ],
    carNum: [
        {
            required: true,
            message: "请输入车牌号",
            trigger: "blur",
        },
    ],
    carDrive: [
        {
            required: true,
            message: "请输入驾驶员名称",
            trigger: "blur",
        },
    ],
})
const config = {
    rules: [
        {
            type: "string",
            required: true,
            message: "请选择发生时间",
        },
    ],
};

// const {
//     resetFields,
//     validate,
//     validateInfos,
// } = useForm(rules);
// const onSubmit = () => {
//     validate().then(() => {
//         console.log(toRaw(rules));
//     }).catch(err => {
//         console.log('error', err);
//     });
// };
/* ------------------拖拽------------------------ */
const modalTitleRef = ref(null);
const {
    x,
    y,
    isDragging,
} = useDraggable(modalTitleRef);


const startX = ref(0);
const startY = ref(0);
const startedDrag = ref(false);
const transformX = ref(0);
const transformY = ref(0);
const preTransformX = ref(0);
const preTransformY = ref(0);
const dragRect = ref({
    left: 0,
    right: 0,
    top: 0,
    bottom: 0,
});
watch([x, y], () => {
    if (!startedDrag.value) {
        startX.value = x.value;
        startY.value = y.value;
        const bodyRect = document.body.getBoundingClientRect();
        const titleRect = modalTitleRef.value.getBoundingClientRect();
        dragRect.value.right = bodyRect.width - titleRect.width;
        dragRect.value.bottom = bodyRect.height - titleRect.height;
        preTransformX.value = transformX.value;
        preTransformY.value = transformY.value;
    }
    startedDrag.value = true;
});
watch(isDragging, () => {
    if (!isDragging) {
        startedDrag.value = false;
    }
});
watchEffect(() => {
    if (startedDrag.value) {
        transformX.value = preTransformX.value + Math.min(Math.max(dragRect.value.left, x.value), dragRect.value.right) - startX.value;
        transformY.value = preTransformY.value + Math.min(Math.max(dragRect.value.top, y.value), dragRect.value.bottom) - startY.value;
    }
});
const transformStyle = computed(() => {
    return {
        transform: `translate(${transformX.value}px, ${transformY.value}px)`,
    };
});
</script>
<style>

</style>